package cn.com.inossem.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.inossem.activity.BaGuaDetailsActivity;
import cn.com.inossem.activity.BaGuaFabuActivity;
import cn.com.inossem.activity.BaGuaSearchActivity;
import cn.com.inossem.activity.BaGuaSheZhiActivity;
import cn.com.inossem.activity.MainActivity;
import cn.com.inossem.activity.R;
import cn.com.inossem.adapter.BaGuaAdapter;
import cn.com.inossem.base.RequestFragment;
import cn.com.inossem.db.DatabaseHelper;
import cn.com.inossem.model.BaGuaListInfoBean;
import cn.com.inossem.pulltorefresh.widget.XListView;
import cn.com.inossem.pulltorefresh.widget.XListView.IXListViewListener;
import cn.com.inossem.requestmanager.WooRequestFactory;
import cn.com.inossem.utils.Utils;

import com.foxykeep.datadroid.requestmanager.Request;

public class BaGuaFragment extends RequestFragment implements
		IXListViewListener, OnClickListener {
	public static BaGuaFragment mf = null;
	private XListView mMessagesList;
	private BaGuaAdapter adapter = null;
	private boolean isRefresh = false;
	public static List<BaGuaListInfoBean> messageInfo;
	ImageView sousuo;
	ImageView jia, imgsave;
	int page = 1;
	boolean shuaxinflag = true;
	String key = "";
	TextView title, shezhi;

	private Handler handler = new Handler() {

		@Override
		public void dispatchMessage(Message msg) {
			// TODO Auto-generated method stub
			super.dispatchMessage(msg);
			switch (msg.what) {
			case 1:
				String str = msg.getData().get("id").toString();
				launchRequest(WooRequestFactory.zanJiekou("", str));
				adapter.notifyDataSetChanged();
				break;
			case 2:
				int position = (Integer) msg.getData().get("position");
				Intent intent = new Intent(getActivity(),
						BaGuaDetailsActivity.class);
				intent.putExtra("position", position);
				startActivityForResult(intent, 0);
				break;
			default:
				break;
			}
		}

	};

	private Handler mHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			adapter.notifyDataSetChanged();
			mMessagesList.stopRefresh();
			mMessagesList.stopLoadMore();
			mMessagesList.setRefreshTime(getTime());
			return false;
		}
	});

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		// if (this.isVisible()) {
		// we check that the fragment is becoming visible
		if (isVisibleToUser) {
			mHasLoadedOnce = true;
			// onVisible();
			// lazyLoad();
		} else {
			mHasLoadedOnce = false;
			// onInvisible();
		}
		// }
		super.setUserVisibleHint(isVisibleToUser);
	}

	@Override
	public void initAllMembers(Bundle savedInstanceState) {
		super.initAllMembers(savedInstanceState);
		System.out.println("第3页" + mHasLoadedOnce);
		mf = this;

		sousuo = (ImageView) mRootView.findViewById(R.id.sousuo);
		sousuo.setOnClickListener(this);
		jia = (ImageView) mRootView.findViewById(R.id.jia);
		jia.setOnClickListener(this);

		ImageView jia = (ImageView) mRootView.findViewById(R.id.jia);
		jia.setOnClickListener(this);

		title = (TextView) mRootView.findViewById(R.id.title);
		shezhi = (TextView) mRootView.findViewById(R.id.shezhi);
		shezhi.setOnClickListener(this);
		
		imgsave = (ImageView) mRootView.findViewById(R.id.imgsave);
		imgsave.setOnClickListener(this);

		mMessagesList = (XListView) mRootView.findViewById(R.id.inspectionList);
		mMessagesList.setPullRefreshEnable(true);
		mMessagesList.setPullLoadEnable(true);
		mMessagesList.setXListViewListener(this);
		mMessagesList.setRefreshTime(getTime());
		mMessagesList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				/*if (Utils.isDenglu == 0) {
				((MainActivity) getActivity()).setPageView(3);
			} else {
				Message me = new Message();
				me.what = 2;
				Bundle bun = new Bundle();
				bun.putInt("position", position);
				me.setData(bun);
				handler.sendMessage(me);
			}*/
			Toast.makeText(getActivity(), "用户名已经存在！", Toast.LENGTH_LONG).show();
			}
		});

		if (mHasLoadedOnce)
			initView();
	}

	public void initView() {
		getInfo();
	}

	public void getInfo() {
		adapter = null;
		messageInfo = new ArrayList<BaGuaListInfoBean>();
		launchRequest(WooRequestFactory.getBagualist(key, page + "", ""));
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		System.out.println("onStart!!!!!");
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		System.out.println("onResume!!!!!");
		// if (shuaxinflag)
		// launchRequest(WooRequestFactory.getBagualist("", page + ""));
		// else
		// shuaxinflag = false;
	}

	private String getTime() {
		return new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA)
				.format(new Date());
	}

	@Override
	public int getContentViewId() {
		// TODO Auto-generated method stub
		return R.layout.bagua_frament;
	}

	// 处理返回值
	@Override
	public void onRequestSucess(Request request, Bundle bundle) {
		super.onRequestSucess(request, bundle);

		if (bundle.containsKey(WooRequestFactory.RESPONSE_BAGUALIST_DATA)) {
			List<BaGuaListInfoBean> retList = bundle
					.getParcelableArrayList(WooRequestFactory.RESPONSE_BAGUALIST_DATA);
			if (retList == null) {
				if (isRefresh) {
					mMessagesList.stopRefresh();
					mMessagesList.stopLoadMore();
					mMessagesList.setRefreshTime(getTime());
					Toast.makeText(getActivity(), "当前是最后一页！", Toast.LENGTH_LONG)
							.show();
					mMessagesList.setPullLoadEnable(false);
				}
				return;
			}
			if (retList.size() > 0) {
				// mInspections.addAll(retList);
				if (retList.size() < 10) {
					mMessagesList.setPullLoadEnable(false);
				}
				if (isRefresh) {
					mMessagesList.stopRefresh();
					mMessagesList.stopLoadMore();
					mMessagesList.setRefreshTime(getTime());
				}
				messageInfo.addAll(retList);

				System.out.println("长度：" + messageInfo.size());
				if (adapter == null) {
					adapter = new BaGuaAdapter(getActivity(), messageInfo,
							handler, false);
					mMessagesList.setAdapter(adapter);
					adapter.notifyDataSetChanged();
				} else {
					adapter.notifyDataSetChanged();
				}

			} else {
				mMessagesList.setPullLoadEnable(false);
				if (isRefresh) {
					mMessagesList.stopRefresh();
					mMessagesList.stopLoadMore();
					mMessagesList.setRefreshTime(getTime());
				}
				if (adapter != null) {
					adapter.notifyDataSetChanged();
				}
			}
		}

	}

	public void charu(String tabname, ContentValues contentValues,
			String whereClause) {
		DatabaseHelper dh = new DatabaseHelper(getActivity());
		SQLiteDatabase db = dh.getWritableDatabase();

		db.update(tabname, contentValues, whereClause, null);

		db.close();
		dh.close();
	}

	@Override
	public void onRefresh() {

		isRefresh = true;
		mMessagesList.setPullLoadEnable(true);
		messageInfo.clear();
		page = 1;
		launchRequest(WooRequestFactory.getBagualist(key, page + "", ""));

	}

	@Override
	public void onLoadMore() {// 加载
		// if (Utils.isDenglu == 0) {
		// ((MainActivity) getActivity()).setPageView(3);
		// return;
		// }
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				isRefresh = true;
				page += 1;
				launchRequest(WooRequestFactory
						.getBagualist(key, page + "", ""));
			}

		}, 2000);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.shezhi:
			Intent intent = new Intent(getActivity(), BaGuaSheZhiActivity.class);
			startActivity(intent);
			break;
		case R.id.jia:
			if (Utils.isDenglu == 0) {
				((MainActivity) getActivity()).setPageView(3);
			} else {
				intent = new Intent(getActivity(), BaGuaFabuActivity.class);
				startActivityForResult(intent, 0);
			}
			break;
		case R.id.sousuo:
			if (Utils.isDenglu == 0) {
				((MainActivity) getActivity()).setPageView(3);
			} else {
				intent = new Intent(getActivity(), BaGuaSearchActivity.class);
				startActivityForResult(intent, 0);
			}
			break;
		default:
			break;
		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		switch (resultCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
		case 1:
			adapter.notifyDataSetChanged();
			break;
		case 2:
			mMessagesList.setPullLoadEnable(true);
			messageInfo.clear();
			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}
			page = 1;
			launchRequest(WooRequestFactory.getBagualist(key, page + "", ""));
			break;
		case 3:
			key = intent.getStringExtra("key");
			title.setText(key);
			mMessagesList.setPullLoadEnable(true);
			messageInfo.clear();
			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}
			page = 1;
			launchRequest(WooRequestFactory.getBagualist(key, page + "", ""));
			break;
		default:
			break;
		}
	}
}
